﻿using System;
using System.ComponentModel;
using System.Configuration;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Net;
using System.Resources;
using System.Threading;
using System.Windows.Forms;
using System.Xml;
using Ionic.Utils.Zip; //this references the open source project www.codeplex.com/dotnetzip which is also licensed under the Microsoft Public License (Ms-PL)  
using System.Reflection;
using System.Collections.Generic;

namespace raktajino
{


    public partial class RAKTAJINO : Form
    {
        #region Globals
        string urlHostingOptions = string.Empty;
        string urlInstallationRequirements = string.Empty;
        string CultureSetting;
        Uri updateURL = null;
        double versionCheckInterval = 0;
        string urlBanner = string.Empty;
        string installingString = string.Empty;
        string installingInfo = string.Empty;
        bool isInstalling = false;
        DateTime progressStartTime;
        int InstallExitCode = -1;
        bool BackgroundInstallCheck = false;
        bool sortProductTreeView = false;
        WebClient downloadclient = null;

        bool isUpdateDialogShown;

        enum EnumInfoPanel { ProductIsAlreadyInstalled, DependencyIsMissing, InstallationCheckErrorHasOccurred, CanInstall, IsInstalling, ClearAll };

        BackgroundWorker wpInstallation = new BackgroundWorker();

        Stack<Package> installPackageStack = new Stack<Package>();
        BackgroundWorker bgInstallPackage = new BackgroundWorker();

        BackgroundWorker wpInstallRequirementsCheckforTreenode = new BackgroundWorker();


        DateTime LastInstallationTime = new DateTime(1965, 6, 21);

        XmlDocument HostingOptions = new XmlDocument();

        public Products Products = null;
        Package currentPackage = null;      //the currently product that is selected in the treeview control
        Package installingPackage = null;   //the currently installing product

        // Declare a Resource Manager instance.
        ResourceManager LocRM = new ResourceManager("raktajino.WinformStrings", typeof(RAKTAJINO).Assembly);
        #endregion

        CultureInfo m_culture = null;
        public CultureInfo Culture
        {
            get
            {
                if (m_culture == null)
                {
                    CultureSetting = ConfigurationSettings.AppSettings["Culture"];
                    try
                    {
                        m_culture = new CultureInfo(CultureSetting);
                    }
                    catch
                    {
                        m_culture = new CultureInfo("en-US");
                    }
                    return m_culture;
                }
                return m_culture;
            }
        }


        public RAKTAJINO()
        {
            InitializeComponent();
        }

        private void RAKTAJINO_Load(object sender, EventArgs e)
        {
            //loading the main form takes a while so we show the user a splashscreen in between.
            SplashScreen splash = new SplashScreen();
            splash.Show();
            

            CultureSetting = ConfigurationSettings.AppSettings["Culture"];
            if (CultureSetting != null)
            {
                CultureInfo ci = new CultureInfo(CultureSetting);
                Thread.CurrentThread.CurrentUICulture = ci;
                Application.CurrentCulture = ci;
            }
            string UIInfo = string.Format("{0}", Thread.CurrentThread.CurrentUICulture.DisplayName);
            toolStripStatusLabelUIInfo.Text = UIInfo;

            #region set localization to controls
            ToolTip tt = new ToolTip();
            tt.SetToolTip(button_open_logs_folder, LocRM.GetString("button_open_logs_folder"));
            label_product.Text = LocRM.GetString("label_product");
            label_category.Text = LocRM.GetString("label_category");
            label_Product_already_installed.Text = LocRM.GetString("label_Product_already_installed");
            label_Product_check_fails.Text = LocRM.GetString("label_Product_check_fails");
            label_Product_dependency_info.Text = LocRM.GetString("label_Product_dependency_info");
            label_Product_installing_info.Text = LocRM.GetString("label_Product_installing_info");
            tabControl1.TabPages[0].Text = LocRM.GetString("TabPage0Text");
            tabControl1.TabPages[1].Text = LocRM.GetString("TabPage1Text");
            tabControl1.TabPages[2].Text = LocRM.GetString("TabPage2Text");
            button_productCheckFailsInfo.Text = LocRM.GetString("button_productCheckFailsInfo");
            //button_goto_product.Text = LocRM.GetString("button_goto_product");
            button_goto_product.Text = LocRM.GetString("button_install");
            button_install.Text = LocRM.GetString("button_install");

            #endregion

            wpInstallRequirementsCheckforTreenode.WorkerSupportsCancellation = true;
            urlHostingOptions = ConfigurationSettings.AppSettings["HostingOptionsURL"];
            urlInstallationRequirements = ConfigurationSettings.AppSettings["InstallationRequirementsURL"];
            urlBanner = ConfigurationSettings.AppSettings["Banner"];

            try
            {
                sortProductTreeView = bool.Parse(ConfigurationSettings.AppSettings["SortProductTreeView"]);
            }
            catch
            {
                sortProductTreeView = false;
            }

            string productDescriptionURL = ConfigurationSettings.AppSettings["ProductDescriptionURL"];
            productDescriptionURL = HelperFunctions.ParseSpecialStrings(productDescriptionURL); //we might want do display different thi
            string sBackgroundInstallCheck = ConfigurationSettings.AppSettings["BackgroundInstallCheck"];
            if (sBackgroundInstallCheck != null)
            {
                BackgroundInstallCheck = Convert.ToBoolean(sBackgroundInstallCheck);
            }


            wpInstallation.DoWork += new DoWorkEventHandler(wpInstallation_DoWork);
            wpInstallation.RunWorkerCompleted += new RunWorkerCompletedEventHandler(wpInstallation_RunWorkerCompleted);
            wpInstallation.ProgressChanged += new ProgressChangedEventHandler(wpInstallation_ProgressChanged);
            wpInstallation.WorkerReportsProgress = true;

            wpInstallRequirementsCheckforTreenode.DoWork += new DoWorkEventHandler(wpInstallRequirementsCheckforTreenode_DoWork);
            wpInstallRequirementsCheckforTreenode.RunWorkerCompleted += new RunWorkerCompletedEventHandler(wpInstallRequirementsCheckforTreenode_RunWorkerCompleted);
            wpInstallRequirementsCheckforTreenode.ProgressChanged += new ProgressChangedEventHandler(wpInstallRequirementsCheckforTreenode_ProgressChanged);
            wpInstallRequirementsCheckforTreenode.WorkerReportsProgress = true;


            //populate banner
            string bannerLocation = string.Format(@"{0}\{1}", Environment.CurrentDirectory, urlBanner);
            if (File.Exists(bannerLocation))
            {
                webBrowser_banner.Navigate(new Uri(bannerLocation));
            }
            else
            {
                webBrowser_banner.DocumentText = string.Format("<html>{0}</html>", this.Name);
            }

            //populate webBrowser product description
            string productDescriptionPath = string.Format(@"{0}\{1}", Environment.CurrentDirectory, productDescriptionURL);
            if (File.Exists(productDescriptionPath))
            {
                webBrowser_product_description.Navigate(new Uri(productDescriptionPath));
            }
            else
            {
                webBrowser_product_description.DocumentText = string.Format("<html>{0}</html>", this.Name);
            }


            if (urlHostingOptions != string.Empty)
            {
                XmlTextReader xr;
                try
                {
                    //replace strings if found in the urlHostingOptions
                    urlHostingOptions = HelperFunctions.ParseSpecialStrings(urlHostingOptions);
                    Uri uri = new Uri(urlHostingOptions, UriKind.RelativeOrAbsolute);
                    if (uri.IsAbsoluteUri)
                    {
                        //for an absolute uri I can ask these props
                        if (uri.IsFile || uri.IsUnc)
                        {
                            //it is a file not a hyperlink
                            xr = new XmlTextReader(urlHostingOptions);
                            HostingOptions.Load(xr);
                        }
                        else if (uri.Scheme == "http")
                        {
                            //hyperlink
                            WebRequest wr = WebRequest.Create(uri);
                            string userAgent = this.ProductName + "/" + this.ProductVersion + @"(%OSNAME%;%LANGUAGE%;%ADDRESSWIDTH%-Bit;%OS%)";
                            userAgent = HelperFunctions.ParseSpecialStrings(userAgent);
                            ((HttpWebRequest)wr).UserAgent = userAgent;
                            wr.Headers.Add("Pragma", "no-cache");
                            wr.Timeout = 20000;
                            // Read the Response
                            WebResponse resp = wr.GetResponse();
                            Stream stream = resp.GetResponseStream();
                            xr = new XmlTextReader(stream);
                            HostingOptions.Load(xr);
                        }
                    }
                    else
                    {
                        //relative uri -> file will be searched in the applications folder
                        xr = new XmlTextReader(urlHostingOptions);
                        HostingOptions.Load(xr);
                    }
                    //done with loading xml document
                }
                catch (Exception ex)
                {
                    MessageBox.Show("HostingOptionsURL: " + urlHostingOptions + "\n" + ex.Message, LocRM.GetString("An_error_has_occurred") + " - " + urlHostingOptions);
                }
            }


            if (HostingOptions.HasChildNodes)
            {
                Products = new Products(HostingOptions);
                if (BackgroundInstallCheck)
                {
                    wpInstallRequirementsCheckforTreenode.RunWorkerAsync();
                    bgReqCheckbar.Visible = true;
                }

                //fill treeview with all products
                FillTreeViewAllProducts();
            }

            this.WindowState = FormWindowState.Maximized;
            splash.Close();
            treeView_products.Focus();

            #region implement check for updates during startup
            try
            {
                versionCheckInterval = double.Parse(ConfigurationSettings.AppSettings["VersionCheckInterval"]);
                updateURL = new Uri(ConfigurationSettings.AppSettings["UpdateURL"]);
                if (versionCheckInterval > 0)
                {
                    UpdateConfig.Instance.UpdateConfigLoadedEvent += new UpdateConfig.UpdateConfigLoadedEventHandler(Instance_UpdateConfigLoadedEvent);
                    UpdateConfig.Instance.LoadConfig(updateURL);
                    System.Timers.Timer versionCheckTimer = new System.Timers.Timer((double)(versionCheckInterval * 1000));
                    versionCheckTimer.Elapsed += new System.Timers.ElapsedEventHandler(versionCheckTimer_Elapsed);
                    versionCheckTimer.Enabled = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(string.Format("{0}\n{1}: {2}", LocRM.GetString("errorWithUpdateConfig"), LocRM.GetString("Error"), ex.Message), LocRM.GetString("Error"));
            }
            #endregion
        }


        void versionCheckTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (updateURL != null)
            {
                UpdateConfig.Instance.LoadConfig(updateURL);
            }
        }

        void Instance_UpdateConfigLoadedEvent()
        {
            if (UpdateConfig.Instance.IsUpdateAvailable)
            {
                CheckForUpdates();
            }
        }

        private void CheckForUpdates()
        {
            if (!isUpdateDialogShown && !isInstalling)
            {
                isUpdateDialogShown = true;
                UpdateDialog updateDialog = new UpdateDialog();
                updateDialog.HostingOptionsURL = urlHostingOptions;
                updateDialog.Culture = CultureSetting;
                updateDialog.UpdateURL = updateURL.AbsoluteUri;
                updateDialog.InstallationRequirementsURL = urlInstallationRequirements;
                updateDialog.VersionCheckInterval = string.Format("{0:0}", versionCheckInterval);
                DialogResult dr = updateDialog.ShowDialog();
                if (dr == DialogResult.OK)
                {
                    //upgrade running close mainapp
                    Application.Exit();
                }
                isUpdateDialogShown = false;
            }
        }

        #region Backgroundworker functions
        void wpInstallRequirementsCheckforTreenode_DoWork(object sender, DoWorkEventArgs e)
        {
            int i = 0;
            progressStartTime = DateTime.Now;

            foreach (Package item in Products.Packages)
            {
                if (item != null)
                {
                    //if (item.InstallationRequirements == null) item.CheckRequirements();
                    item.CheckRequirements();  //yes I want every item to be checked -> as this would make sense e.g. after an installation
                    int percentage = (i * 100) / Products.Packages.Count;
                    ProgressChangedEventArgs ProgressChangedArgs = new ProgressChangedEventArgs(percentage, e);
                    i++;
                    wpInstallRequirementsCheckforTreenode.ReportProgress(percentage, e);
                }
            }
        }
        void wpInstallRequirementsCheckforTreenode_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            //Update Treeview at TabPage_all Icons at each 5 % progess
            if (e.ProgressPercentage % 5 == 0)
            {
                this.Invoke(new EventHandler(AssignAllTreeNodeIcons));
            }
            bgReqCheckbar.Value = e.ProgressPercentage;
            toolStripStatusLabel_status.Text = LocRM.GetString("Checking_Installation_Requirements");
        }
        void wpInstallRequirementsCheckforTreenode_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            bgReqCheckbar.Visible = false;
            toolStripStatusLabel_status.Text = string.Empty;

            this.Invoke(new EventHandler(AssignAllTreeNodeIcons));
        }
        void wpInstallation_DoWork(object sender, DoWorkEventArgs e)
        {
            #region Installation
            InstallAction Action = GetNextRemainingInstallAction();

            if (Action == null)
            {
                e.Cancel = true;
                return;
            }

            ProcessStartInfo startInfo = new ProcessStartInfo(Action.Command.Command);
            startInfo.Arguments = Action.Command.Arguments;

            //Is the action an unzip job - if so do the work and return.
            if (Action.Command.Command.Contains("UNZIP"))
            {
                try
                {
                    string[] parameters = Action.Command.Arguments.Split('@');
                    if (parameters.Length < 3)
                    {
                        throw new ArgumentException(string.Format(LocRM.GetString("label_Product_cannot_be_installed") + ":{0}", Action.Command.Arguments));
                    }
                    string zipfilename = parameters[1].ToString();
                    string outputfolder = parameters[2].ToString();
                    //localization
                    if (!File.Exists(zipfilename)) throw new ArgumentException(string.Format(LocRM.GetString("Zip_file_cannot_be_found") + ": {0}", zipfilename));
                    ZipFile zip = new ZipFile(zipfilename);
                    System.IO.FileInfo fi = new System.IO.FileInfo(zipfilename);
                    decimal size = (decimal)fi.Length;
                    int unzippedsize = 0;
                    progressStartTime = DateTime.Now;
                    installingString = string.Format(LocRM.GetString("Unzipping") + ": {0}", zipfilename);
                    foreach (ZipEntry entry in zip)
                    {
                        // unzip and inform the user what we are currently doing
                        int percentageCompleted = (int)((decimal)(100 / size) * unzippedsize);
                        wpInstallation.ReportProgress(percentageCompleted, installingString);
                        entry.Extract(outputfolder);
                        unzippedsize += entry.CompressedSize;
                    }
                    Action.ExitCode = 0;
                    zip.Dispose();
                    Action.ExitInfoString = LocRM.GetString("UNZIP_successful");
                }
                catch (SystemException se)
                {
                    //localization
                    Action.ExitInfoString = string.Format(LocRM.GetString("Error_during_unzip") + ":\n{0}", se.Message);
                }
                finally
                {
                    installingString = string.Empty;
                    Action.done = true;
                    e.Result = Action;
                }
                return;
            }

            //the action is no unzip - we do have to launch another process to carry out the action
            if (Action.Command.Command.Contains("cmd.exe"))
            {
                startInfo.UseShellExecute = true;
                startInfo.WindowStyle = ProcessWindowStyle.Hidden;
                startInfo.RedirectStandardError = false;
                startInfo.RedirectStandardOutput = false;
                startInfo.WorkingDirectory = Environment.GetFolderPath(Environment.SpecialFolder.System);
            }
            else
            {
                startInfo.UseShellExecute = false;
                startInfo.RedirectStandardError = true;
                startInfo.RedirectStandardOutput = true;
            }
            Process InstallationProcess = new Process();
            InstallationProcess.StartInfo = startInfo;

            try
            {
                InstallationProcess.Start();
                isInstalling = true;
                //installingString = string.Format("{0}", installingPackage.Name);
                progressStartTime = DateTime.Now;
                while (!InstallationProcess.HasExited)
                {
                    // inform the user what we are currently doing
                    wpInstallation.ReportProgress(0, string.Format("{0}", installingPackage.Name));
                    System.Threading.Thread.Sleep(1000);
                }
                //do stuff after installation has exited
                InstallExitCode = InstallationProcess.ExitCode;
                Action.ExitCode = InstallExitCode;
                //localization
                installingInfo = string.Format(LocRM.GetString("Exit_Code") + ": {0}\n" + LocRM.GetString("Exit_Time") + ": {1}", InstallationProcess.ExitCode, InstallationProcess.ExitTime.ToLongTimeString());

            }
            catch (SystemException se)
            {
                //MessageBox.Show(this, string.Format("Error: {0}\r\nCommand:{1}\r\nParameter:{2}", w32ex.Message, Action.Command.Command, Action.Command.Arguments), "Win32 Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Action.ExitInfoString = se.Message;
            }
            finally
            {
                Action.done = true;
                e.Result = Action;
            }
            #endregion
        }

        void wpInstallation_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            // we are basically showing what we are currently doing
            string installingPackageName = e.UserState as string;

            TimeSpan ts = (DateTime.Now - progressStartTime);

            //localization
            installingString = string.Format(LocRM.GetString("Installing") + ": {0} ({1:F0} s)", installingPackageName, ts.TotalSeconds);
            switch (ts.Seconds % 3)
            {
                case 0:
                    installingString += " .";
                    break;
                case 1:
                    installingString += " ..";
                    break;
                case 2:
                    installingString += " ...";
                    break;
            }

            toolStripStatusLabel_status.Text = installingString;
            bgReqCheckbar.Visible = false;


        }
        void wpInstallation_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            installingString = string.Empty;
            installingInfo = string.Empty;

            LastInstallationTime = DateTime.Now;


            if (e.Cancelled)
            {
                // in this case the Package has been installed during this session
                // therefore we do not get a package back and leave the installation routine

                //show UI back to user
                InstallationCleanup();
                string msg = string.Format(LocRM.GetString("Error_in_Action_Already_installed"));
                for (int i = 0; i < this.installingPackage.InstallationActions.Count; i++)
                {
                    msg += "\n InstallationCommand: " + this.installingPackage.InstallationActions[i].Command.Command + this.installingPackage.InstallationActions[i].Command.Arguments;
                }
                MessageBox.Show(msg, LocRM.GetString("Install_Action_failed"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }


            // the backgroundworker gives us the result as an Installaction
            // we can determine what happend 
            InstallAction ActionJustFinished = e.Result as InstallAction;

            if (ActionJustFinished.ExitCode != 0)
            {
                //localization
                InstallationCleanup();
                string msg = string.Format(LocRM.GetString("Error") + " {0} " + LocRM.GetString("in_Action") + " {1} {2}\n{3}", ActionJustFinished.ExitCode, ActionJustFinished.Command.Command, ActionJustFinished.Command.Arguments, ActionJustFinished.ExitInfoString);
                MessageBox.Show(msg, LocRM.GetString("Install_Action_failed"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            InstallAction Action = GetNextRemainingInstallAction();

            // if there is another Action
            // we start a new background thread
            // otherwise we finish with the installation routine

            if (Action != null)
            {
                //SetControlsToForInstallation(true);
                wpInstallation.RunWorkerAsync();
                bgReqCheckbar.Visible = false;
                return;
            }

            InstallationCleanup();


        }


        delegate void InstallationCleanupCallback();
        private void InstallationCleanup()
        {
            if (InvokeRequired)
            {
                InstallationCleanupCallback d = new InstallationCleanupCallback(InstallationCleanup);
                this.Invoke(d);
            }
            else
            {
                isInstalling = false;
                bgReqCheckbar.Visible = false;
                SetControlsToForInstallation(false);
                //reset all actions within the installed package so that it can be installed again.
                foreach (InstallAction singleAction in this.installingPackage.InstallationActions)
                {
                    singleAction.done = false;
                }

                //update requirementschecking after installation  
                if (BackgroundInstallCheck)
                {
                    if (!wpInstallRequirementsCheckforTreenode.IsBusy)
                    {
                        HelperFunctions.CachedCheckInstallationRequirements.Clear(); //clear installation requirements cache before scanning
                        wpInstallRequirementsCheckforTreenode.RunWorkerAsync();
                        bgReqCheckbar.Visible = true;
                    }
                };
            }

        }
        #endregion


        #region helper functions
        private InstallAction GetNextRemainingInstallAction()
        {
            InstallAction Action = null;

            foreach (InstallAction singleAction in this.installingPackage.InstallationActions)
            {
                if (!singleAction.done)
                {
                    Action = singleAction;
                    break;
                }
            }
            return Action;
        }
        private void FillTreeViewAllProducts()
        {
            int index;
            TreeNode tn;

            TreeView currentTreeView = treeView_products;
            currentTreeView = treeView_products;
            currentTreeView.BeginUpdate();
            currentTreeView.Nodes.Clear();

            foreach (Package item in Products.Packages)
            {
                foreach (string category in item.CategoryList)
                {
                    TreeNode catTN = new TreeNode();
                    tn = new TreeNode(item.Name);
                    tn.Tag = item;
                    int subindex;
                    if (!currentTreeView.Nodes.ContainsKey(category))
                    {
                        catTN = currentTreeView.Nodes.Add(category);
                        catTN.Name = category;
                        index = catTN.Index;
                        subindex = catTN.Nodes.Add(tn);
                        catTN.Nodes[subindex].Name = item.Name;
                    }
                    else
                    {
                        index = currentTreeView.Nodes.IndexOfKey(category);
                        subindex = currentTreeView.Nodes[index].Nodes.Add(tn);
                        currentTreeView.Nodes[index].Nodes[subindex].Name = item.Name;
                    }

                    if (item.InstallationRequirements != null)
                    {
                        AssignTreeNodeIcon(tn);
                    }
                    else
                    {
                        tn.StateImageIndex = 5;
                    }
                }
            }
            currentTreeView.ExpandAll();
            currentTreeView.ShowPlusMinus = false;
            currentTreeView.ShowRootLines = false;
            currentTreeView.ShowLines = true;

            if (sortProductTreeView) treeView_products.Sort();
            treeView_products.EndUpdate();
        }
        private void AssignAllTreeNodeIcons(object sender, EventArgs e)
        {

            TreeView currentTreeView = null;

            switch (tabControl1.SelectedTab.Name)
            {
                case "tabPage_all":
                    currentTreeView = treeView_products;
                    break;
                case "tabPage_installed":
                    currentTreeView = treeView_installed;
                    break;
                case "tabPage_installable":
                    currentTreeView = treeView_installable;
                    break;
            }
            currentTreeView.BeginUpdate();
            foreach (TreeNode tn in currentTreeView.Nodes)
            {
                //subnoded
                if (tn.Tag == null)
                {
                    TreeNodeCollection tnCol = tn.Nodes;
                    foreach (TreeNode subTN in tnCol)
                        AssignTreeNodeIcon(subTN);
                }
            }
            currentTreeView.EndUpdate();
        }
        private static void AssignTreeNodeIcon(TreeNode tn)
        {
            Package package = (Package)tn.Tag;
            if (package.InstallationRequirements != null)
            {
                if (package.InstallationRequirements.InstallCheckRequired && package.InstallationRequirements.isValidInstallationRequirements == true)
                {
                    if (package.InstallationRequirements.InstallCheckSuccessfull)
                    {
                        tn.StateImageIndex = 0;
                        tn.ForeColor = Color.Black;
                    }
                    else
                    {
                        tn.StateImageIndex = 2;
                        tn.ForeColor = Color.Gray;
                    }
                    if (package.InstallationRequirements.ProductAlreadyInstalled)
                    {
                        tn.StateImageIndex = 3;
                        tn.ForeColor = Color.Gray;
                    }

                }
                else
                {
                    tn.StateImageIndex = 5;
                    tn.ForeColor = Color.Gray;
                }
            }
            else
            {
                tn.StateImageIndex = 5;
                tn.ForeColor = Color.Gray;
            }
        }
        #endregion


        #region Control functions

        void treeView_products_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (!isInstalling)
            {
                button_install.Visible = false;
                button_install.Image = imageList_icons.Images[0];
                button_install.ImageAlign = ContentAlignment.BottomRight;
            }

            installingInfo = string.Empty;

            this.currentPackage = (Package)e.Node.Tag;

            //this should not happen - in case it does show generic page to user and leave this function
            if (this.currentPackage == null)
            {
                Type t = typeof(raktajino.Package);
                string[] asminfo = t.Assembly.ToString().Split(",".ToCharArray());
                //localization
                string text = string.Format(LocRM.GetString("HTML_Currently_no_package_selected"));
                //string text = string.Format("<H1>Currently no package selected</H1><hr/>");
                text += string.Format("<FONT style='font-size:x-small'> {0} </FONT>", asminfo[1]);
                webBrowser_product_description.DocumentText = text;
                return;
            }

            if (!string.IsNullOrEmpty(this.currentPackage.DescriptionUrl))
            {
                webBrowser_product_description.Navigate(new Uri(this.currentPackage.DescriptionUrl));
            }
            else
            {
                webBrowser_product_description.DocumentText = this.currentPackage.Displaytext;
            }


            if (BackgroundInstallCheck)
            {
                if (this.currentPackage.InstallationRequirements == null)
                {
                    this.currentPackage.CheckRequirements();
                }
                TimeSpan timesincelastInstall = (this.LastInstallationTime - this.currentPackage.InstallationRequirements.LastCheckTime);
                if (timesincelastInstall.TotalSeconds > 0) this.currentPackage.CheckRequirements();
            }
            else
            {
                this.currentPackage.CheckRequirements();
            }


            //if the Installation Requirements check failed for this package for whatever reason show this to the user and leave.
            if (!this.currentPackage.InstallationRequirements.isValidInstallationRequirements)
            {
                //CheckRequirements fails this should not happen show "?" to the user
                ShowCorrectInfoPanel(EnumInfoPanel.InstallationCheckErrorHasOccurred);
                return;
            }


            //the Installation Requirements check returned valid information - now show this to the user.
            if (this.currentPackage.InstallationRequirements.InstallCheckSuccessfull)
            {
                if (!isInstalling)
                {
                    button_install.Visible = true;
                    button_install.Image = imageList_icons.Images[1];
                    button_install.ImageAlign = ContentAlignment.BottomRight;
                }
            }

            if (this.currentPackage.InstallationRequirements.ProductAlreadyInstalled)
            {
                installingInfo = "Product is installed!\n";
                ShowCorrectInfoPanel(EnumInfoPanel.ProductIsAlreadyInstalled);
            }
            else
            {
                switch (this.currentPackage.InstallationRequirements.InstallCheckSuccessfull)
                {
                    case true:
                        installingInfo = "Product can be installed!\n";
                        ShowCorrectInfoPanel(EnumInfoPanel.CanInstall);
                        break;
                    case false:
                        installingInfo = "Product cannot be installed!\n";
                        if (!isInstalling)
                        {
                            ShowCorrectInfoPanel(EnumInfoPanel.DependencyIsMissing);
                            comboBox1.Items.Clear();
                        }

                        for (int i = 0; i < this.currentPackage.InstallationRequirements.MissingRequirements.Count; i++)
                        {
                            if (this.currentPackage.CategoryList.Count > 0)
                            {
                                for (int x = 0; x < Products.Packages.Count; x++)
                                {
                                    if (Products.Packages[x].SelfCheck == this.currentPackage.InstallationRequirements.MissingRequirements[i])
                                    {
                                        if (this.currentPackage.Name != Products.Packages[x].Name)
                                        {
                                            comboBox1.Items.Add(Products.Packages[x].Name);
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                        if (comboBox1.Items.Count > 0) comboBox1.SelectedIndex = 0;
                        break;
                }
            }
        }

        private void ShowCorrectInfoPanel(EnumInfoPanel whichInfoPanel)
        {
            SuspendLayout();

            if (isInstalling)
                whichInfoPanel = EnumInfoPanel.IsInstalling;

            switch (whichInfoPanel)
            {
                case EnumInfoPanel.CanInstall:
                    button_goto_product.Visible = false;
                    panel_Product_dependency_info_all.Visible = false;
                    panel_Product_already_installed_all.Visible = false;
                    panel_Product_installing_info_all.Visible = false;
                    panel_Product_check_fails_all.Visible = false;
                    button_productCheckFailsInfo.Visible = false;
                    panel_Product_dependency_info.Visible = false;
                    panel_Product_installing_info.Visible = false;
                    panel_Product_already_installed.Visible = false;
                    panel_Product_check_fails.Visible = false;
                    button_install.Visible = true;
                    break;
                case EnumInfoPanel.DependencyIsMissing:
                    panel_Product_check_fails.Visible = false;
                    panel_Product_check_fails_all.Visible = false;
                    button_productCheckFailsInfo.Visible = false;
                    panel_Product_already_installed.Visible = false;
                    panel_Product_already_installed_all.Visible = false;
                    panel_Product_installing_info_all.Visible = false;
                    panel_Product_installing_info.Visible = false;
                    button_goto_product.Visible = true; ;
                    panel_Product_dependency_info.Visible = true;
                    panel_Product_dependency_info_all.Visible = true;
                    break;
                case EnumInfoPanel.InstallationCheckErrorHasOccurred:
                    panel_Product_already_installed.Visible = false;
                    panel_Product_already_installed_all.Visible = false;
                    panel_Product_dependency_info_all.Visible = false;
                    panel_Product_dependency_info.Visible = false;
                    panel_Product_installing_info_all.Visible = false;
                    panel_Product_installing_info.Visible = false;
                    button_productCheckFailsInfo.Visible = true;
                    panel_Product_check_fails.Visible = true;
                    panel_Product_check_fails_all.Visible = true;
                    button_productCheckFailsInfo.Visible = true;
                    break;
                case EnumInfoPanel.ProductIsAlreadyInstalled:
                    button_goto_product.Visible = false;
                    button_install.Visible = false;
                    panel_Product_check_fails_all.Visible = false;
                    button_productCheckFailsInfo.Visible = false;
                    panel_Product_check_fails.Visible = false;
                    panel_Product_dependency_info_all.Visible = false;
                    panel_Product_dependency_info.Visible = false;
                    panel_Product_installing_info_all.Visible = false;
                    panel_Product_installing_info.Visible = false;
                    panel_Product_already_installed.Visible = true;
                    panel_Product_already_installed_all.Visible = true;
                    break;
                case EnumInfoPanel.IsInstalling:
                    this.WindowState = FormWindowState.Minimized;
                    this.notifyIcon1.Visible = true;
                    ShowRaktajinoBallonTip();
                    button_goto_product.Visible = false;
                    button_install.Visible = false;
                    panel_Product_check_fails_all.Visible = false;
                    button_productCheckFailsInfo.Visible = false;
                    panel_Product_check_fails.Visible = false;
                    panel_Product_dependency_info_all.Visible = false;
                    panel_Product_dependency_info.Visible = false;
                    panel_Product_already_installed.Visible = false;
                    panel_Product_already_installed_all.Visible = false;
                    panel_Product_installing_info.Visible = true;
                    panel_Product_installing_info_all.Visible = true;
                    break;
                case EnumInfoPanel.ClearAll:
                    this.WindowState = FormWindowState.Normal;
                    this.notifyIcon1.Visible = false;
                    button_goto_product.Visible = false;
                    button_install.Visible = false;
                    panel_Product_check_fails_all.Visible = false;
                    button_productCheckFailsInfo.Visible = false;
                    panel_Product_check_fails.Visible = false;
                    panel_Product_dependency_info_all.Visible = false;
                    panel_Product_dependency_info.Visible = false;
                    panel_Product_already_installed.Visible = false;
                    panel_Product_already_installed_all.Visible = false;
                    panel_Product_installing_info.Visible = false;
                    panel_Product_installing_info_all.Visible = false;
                    break;
            }
            ResumeLayout();

        }

        private void ShowRaktajinoBallonTip()
        {
            if (!string.IsNullOrEmpty(this.installingPackage.Name))
            {
                notifyIcon1.ShowBalloonTip(5000, Application.ProductName, LocRM.GetString("Installing") + " : " + this.installingPackage.Name, ToolTipIcon.Info);
            }
        }
        private void button_install_Click(object sender, EventArgs e)
        {

            if (this.currentPackage == null)
            {
                MessageBox.Show(this, LocRM.GetString("No_Package_selected"), "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            //this is the package we are going to install
            this.installingPackage = this.currentPackage;

            //Eula dialog
            if (!string.IsNullOrEmpty(this.currentPackage.EulaUrl))
            {
                UserEulaDialog dlgUserEula = new UserEulaDialog();
                dlgUserEula.installingPackage = this.installingPackage;
                DialogResult dr = dlgUserEula.ShowDialog(this);

                if (dr != DialogResult.OK) return;
            }


            if (this.installingPackage.UserInput.Required)
            {
                UserInputDialog dlgUserInput = new UserInputDialog();
                dlgUserInput.installingPackage = this.installingPackage;
                DialogResult dr = dlgUserInput.ShowDialog(this);

                if (dr != DialogResult.OK) return;
            }

            this.installingPackage.GetInstallationCommand();

            SetControlsToForInstallation(true);

            //do download if necessary
            if (this.installingPackage.DownloadUrl != null)
            {
                downloadclient = new WebClient();
                downloadclient.DownloadFileCompleted += new AsyncCompletedEventHandler(downloadclient_DownloadFileCompleted);
                downloadclient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(downloadclient_DownloadProgressChanged);
                string filePath = this.installingPackage.InstallationUrl + "\\" + System.IO.Path.GetFileName(this.installingPackage.DownloadUrl.LocalPath);
                if (!Directory.Exists(Path.GetDirectoryName(filePath)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(filePath));
                }
                progressStartTime = DateTime.Now;
                downloadclient.DownloadFileAsync(this.installingPackage.DownloadUrl, filePath, this.installingPackage.DownloadUrl);
                bgReqCheckbar.Visible = true;
            }
            else
            {
                wpInstallation.RunWorkerAsync();
                bgReqCheckbar.Visible = false;
            }
        }

        void downloadclient_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            if (wpInstallRequirementsCheckforTreenode.IsBusy)
            {
                wpInstallRequirementsCheckforTreenode.CancelAsync();
            }
            installingString = string.Format(LocRM.GetString("Downloading") + ": {0} ({1}%)", ((WebClient)sender).BaseAddress, e.ProgressPercentage);
            toolStripStatusLabel_status.Text = installingString;
            bgReqCheckbar.Value = e.ProgressPercentage;
        }
        void downloadclient_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {
            installingString = string.Empty;
            if (e.Error != null)
            {
                Uri uri = e.UserState as Uri;
                MessageBox.Show(string.Format("{0}:{1}\n{2}\n{3}", LocRM.GetString("A_download_error_has_occurred"), uri, e.Error.Message, LocRM.GetString("Error"), LocRM.GetString("Installation_aborted")));
                SetControlsToForInstallation(false);
            }
            else
            { // start intstallation 
                wpInstallation.RunWorkerAsync();
            }
            bgReqCheckbar.Visible = false;
        }

        private void enable_button_install(object sender, EventArgs e)
        {
            button_install.Visible = !isInstalling;
            button_install.Image = null;
            treeView_products_NodeMouseClick(this, new TreeNodeMouseClickEventArgs(treeView_products.SelectedNode, MouseButtons.Left, 1, 0, 0));
        }
        private void splitContainer2_Panel2_DoubleClick(object sender, EventArgs e)
        {
            #region DEBUGHACK
#if DEBUG
            if (this.currentPackage != null)
            {


                if (this.currentPackage.UserInput.Required)
                {
                    UserInputDialog dlgUserInput = new UserInputDialog();
                    dlgUserInput.installingPackage = this.currentPackage;
                    DialogResult dr = dlgUserInput.ShowDialog(this);

                    if (dr != DialogResult.OK) return;

                }

                this.currentPackage.GetInstallationCommand();

                string msg = string.Empty;
                int i = 0;
                foreach (InstallAction singleAction in this.currentPackage.InstallationActions)
                {
                    i++;
                    msg = string.Format("{3} {2}: {0} {1}", singleAction.Command.Command, singleAction.Command.Arguments, i, LocRM.GetString("Action"));
                    MessageBox.Show(msg);

                }

            }
#endif
            #endregion
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            toolStripStatusLabel_Time.Text = DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToLongTimeString();
        }

        //--------------------------touched bfrank

        private void button_goto_product_Click(object sender, EventArgs e)
        {
            //fill the queue of with packages to install
            Queue<Package> packageQueue = new Queue<Package>();

            for (int i = 0; i < this.currentPackage.InstallationRequirements.MissingRequirements.Count; i++)
            {
                if (this.currentPackage.CategoryList.Count > 0)
                {
                    for (int x = 0; x < Products.Packages.Count; x++)
                    {
                        if (Products.Packages[x].SelfCheck == this.currentPackage.InstallationRequirements.MissingRequirements[i])
                        {
                            if (this.currentPackage.Name != Products.Packages[x].Name)
                            {
                                packageQueue.Enqueue(Products.Packages[x]);
                                break;
                            }
                        }
                    }
                }
            }

            //start the installation thread
            packageQueue.Enqueue(this.currentPackage);
            installingPackage = packageQueue.Peek();
            SetControlsToForInstallation(true);
            Thread installerthread = new Thread(delegate()
                {
                    while (packageQueue.Count > 0)
                    {
                        installingPackage = packageQueue.Dequeue();
                        try
                        {
                            this.installingPackage.PackageInstallationProgressChangedEvent += new Package.PackageInstallationProgressChangedEventHandler(installingPackage_PackageInstallationProgressChangedEvent);
                            this.installingPackage.PackageInstallationCompletedEvent += new Package.PackageInstallationCompletedEventHandler(installingPackage_PackageInstallationCompletedEvent);
                            this.installingPackage.InstallPackage();
                        }
                        catch (Exception ex)
                        {
                            string mbox = string.Format("{0}: {1}", LocRM.GetString("Error", Culture), installingPackage.Name);
                            MessageBox.Show(ex.Message, mbox);
                            break;
                        }
                        finally
                        {
                            this.installingPackage.PackageInstallationProgressChangedEvent -= new Package.PackageInstallationProgressChangedEventHandler(installingPackage_PackageInstallationProgressChangedEvent);
                            this.installingPackage.PackageInstallationCompletedEvent -= new Package.PackageInstallationCompletedEventHandler(installingPackage_PackageInstallationCompletedEvent);
                        }
                    }
                    SetControlsToForInstallation(false);
                    //update requirementschecking after installation  
                    if (BackgroundInstallCheck)
                    {
                        if (!wpInstallRequirementsCheckforTreenode.IsBusy)
                        {
                            HelperFunctions.CachedCheckInstallationRequirements.Clear(); //clear installation requirements cache before scanning
                            wpInstallRequirementsCheckforTreenode.RunWorkerAsync();
                            bgReqCheckbar.Visible = true;
                        }
                    };
                });
            installerthread.Name = "installer";
            installerthread.Start();
            return;


            //navigates to tabPage_all finds the combobox element and then selects it 
            //if (comboBox1.SelectedItem != null)
            //{
            //    tabControl1.SelectedTab = tabControl1.TabPages["tabPage_all"];

            //    TreeNode selectedTN = null;
            //    TreeNode[] foundTNCol;
            //    foundTNCol = treeView_products.Nodes.Find(comboBox1.SelectedItem.ToString(), true);

            //    if (foundTNCol != null)
            //    {
            //        selectedTN = foundTNCol[0];
            //        treeView_products.SelectedNode = selectedTN;
            //        treeView_products_NodeMouseClick(this, new TreeNodeMouseClickEventArgs(selectedTN, MouseButtons.Left, 1, 0, 0));
            //    }
            //}
        }

        void installingPackage_PackageInstallationCompletedEvent(object sender, AsyncCompletedEventArgs e)
        {
            lock (installingString)
            {
                string userstate = e.UserState as string;
                installingString = string.Format("{0}", userstate);

                if (e.Error != null || e.Cancelled == true)
                {
                    MessageBox.Show(installingString, LocRM.GetString("Error", Culture));
                }
            }
            UpdateStatusBar(installingString, int.MaxValue);  //thread safe calling
        }

        void installingPackage_PackageInstallationProgressChangedEvent(object sender, ProgressChangedEventArgs e)
        {
            lock (installingString)
            {
                string userstate = e.UserState as string;
                installingString = string.Format("{0}", userstate);
                UpdateStatusBar(installingString, e.ProgressPercentage);  //thread safe calling
            }
        }



        delegate void SetStatusStripCallback(string toolStripStatusLabel_status_Text, int bgReqCheckbar_value);

        private void UpdateStatusBar(string message, int progressPercentage)
        {
            if (this.statusStrip1.InvokeRequired)
            {
                SetStatusStripCallback d = new SetStatusStripCallback(UpdateStatusBar);
                //this.Invoke(d, new object[] { "blubb",1 });
                this.Invoke(d, new object[] { message,progressPercentage });
            }
            else
            {
                toolStripStatusLabel_status.Text = message;
                if (progressPercentage <= 100 && progressPercentage >= 0)
                {
                    bgReqCheckbar.Value = progressPercentage;
                    bgReqCheckbar.Visible = true;
                }
                else
                {
                    bgReqCheckbar.Visible = false;
                }
            }
        }

        //----------------------------

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            //no products information could be retrieved - return
            if (Products == null) return;

            TreeView currentTreeView = null;
            int index;
            TreeNode tn;

            switch (tabControl1.SelectedTab.Name)
            {
                case "tabPage_all":
                    if (tabControl1.SelectedTab.Controls.Contains(treeView_products))
                    {
                        //treeview found do stuff
                        currentTreeView = treeView_products;
                        currentTreeView.BeginUpdate();
                        currentTreeView.Nodes.Clear();
                        foreach (Package item in Products.Packages)
                        {
                            foreach (string category in item.CategoryList)
                            {
                                TreeNode catTN = new TreeNode();
                                tn = new TreeNode(item.Name);
                                tn.Tag = item;
                                int subindex;
                                if (!currentTreeView.Nodes.ContainsKey(category))
                                {
                                    catTN = currentTreeView.Nodes.Add(category);
                                    catTN.Name = category;
                                    index = catTN.Index;
                                    subindex = catTN.Nodes.Add(tn);
                                    catTN.Nodes[subindex].Name = item.Name;
                                }
                                else
                                {
                                    index = currentTreeView.Nodes.IndexOfKey(category);
                                    subindex = currentTreeView.Nodes[index].Nodes.Add(tn);
                                    currentTreeView.Nodes[index].Nodes[subindex].Name = item.Name;
                                }
                                AssignTreeNodeIcon(tn);
                            }
                        }
                        currentTreeView.ExpandAll();
                        currentTreeView.ShowPlusMinus = false;
                        currentTreeView.ShowRootLines = false;
                        currentTreeView.ShowLines = true;
                    }
                    break;
                case "tabPage_installed":
                    if (tabControl1.SelectedTab.Controls.Contains(treeView_installed))
                    {
                        currentTreeView = treeView_installed;
                        currentTreeView.BeginUpdate();
                        currentTreeView.Nodes.Clear();
                        foreach (Package item in Products.Packages)
                        {
                            if (item.InstallationRequirements != null)
                            {
                                if (item.InstallationRequirements.ProductAlreadyInstalled)
                                {
                                    foreach (string category in item.CategoryList)
                                    {
                                        TreeNode catTN = new TreeNode();
                                        tn = new TreeNode(item.Name);
                                        tn.Tag = item;
                                        int subindex;
                                        if (!currentTreeView.Nodes.ContainsKey(category))
                                        {
                                            catTN = currentTreeView.Nodes.Add(category);
                                            catTN.Name = category;
                                            index = catTN.Index;
                                            subindex = catTN.Nodes.Add(tn);
                                            catTN.Nodes[subindex].Name = item.Name;
                                        }
                                        else
                                        {
                                            index = currentTreeView.Nodes.IndexOfKey(category);
                                            subindex = currentTreeView.Nodes[index].Nodes.Add(tn);
                                            currentTreeView.Nodes[index].Nodes[subindex].Name = item.Name;
                                        }
                                        currentTreeView.Nodes[index].Nodes[subindex].StateImageIndex = 3;
                                    }
                                }
                            }
                        }
                        currentTreeView.ShowPlusMinus = false;
                        currentTreeView.ShowLines = true;
                        currentTreeView.ExpandAll();
                    }
                    break;

                case "tabPage_installable":
                    if (tabControl1.SelectedTab.Controls.Contains(treeView_installable))
                    {
                        currentTreeView = treeView_installable;
                        currentTreeView.BeginUpdate();
                        currentTreeView.Nodes.Clear();
                        foreach (Package item in Products.Packages)
                        {
                            if (item.InstallationRequirements != null)
                            {
                                if (item.InstallationRequirements.InstallCheckSuccessfull)
                                {
                                    foreach (string category in item.CategoryList)
                                    {
                                        TreeNode catTN = new TreeNode();
                                        tn = new TreeNode(item.Name);
                                        tn.Tag = item;
                                        int subindex;
                                        if (!currentTreeView.Nodes.ContainsKey(category))
                                        {
                                            catTN = currentTreeView.Nodes.Add(category);
                                            catTN.Name = category;
                                            index = catTN.Index;
                                            subindex = catTN.Nodes.Add(tn);
                                            catTN.Nodes[subindex].Name = item.Name;
                                        }
                                        else
                                        {
                                            index = currentTreeView.Nodes.IndexOfKey(category);
                                            subindex = currentTreeView.Nodes[index].Nodes.Add(tn);
                                            currentTreeView.Nodes[index].Nodes[subindex].Name = item.Name;
                                        }
                                        currentTreeView.Nodes[index].Nodes[subindex].StateImageIndex = 0;
                                    }
                                }
                            }
                        }
                        currentTreeView.ShowPlusMinus = true;
                        currentTreeView.ShowLines = true;
                        currentTreeView.ExpandAll();
                    }
                    break;
            }

            if (sortProductTreeView) currentTreeView.Sort();
            currentTreeView.EndUpdate();
        }

        delegate void SetControlsToForInstallationCallback(bool installing);
        private void SetControlsToForInstallation(bool installing)
        {
            if (InvokeRequired)
            {
                SetControlsToForInstallationCallback d = new SetControlsToForInstallationCallback(SetControlsToForInstallation);
                this.Invoke(d, installing);
            }
            else
            {
                button_install.Visible = installing;

                bool disableTabControlDuringInstall = false;
                string DisableTabControlDuringInstall = ConfigurationSettings.AppSettings["DisableTabControlDuringInstall"];
                if (DisableTabControlDuringInstall != null)
                {
                    disableTabControlDuringInstall = Convert.ToBoolean(DisableTabControlDuringInstall);
                }

                if (installing)
                {
                    this.Cursor = Cursors.WaitCursor;
                    ShowCorrectInfoPanel(EnumInfoPanel.IsInstalling);
                    if (disableTabControlDuringInstall) tabControl1.Enabled = false;
                }
                else
                {
                    ShowCorrectInfoPanel(EnumInfoPanel.ClearAll);
                    TreeNode installedNode = treeView_products.Nodes[installingPackage.Name];
                    if (installedNode != null)
                        treeView_products_NodeMouseClick(this, new TreeNodeMouseClickEventArgs(installedNode, MouseButtons.Left, 1, 0, 0));
                    this.Cursor = Cursors.Default;
                    tabControl1.Enabled = true;
                }
            }
        }
        private void button_productCheckFailsInfo_Click(object sender, EventArgs e)
        {
            string details = string.Empty;

            foreach (string substr in this.currentPackage.InstallationRequirements.CheckResults)
            {
                details += substr + "\n";
            }
            MessageBox.Show(details, LocRM.GetString("Verification_check_failed"));
        }
        #endregion

        private void button_open_logs_folder_Click(object sender, EventArgs e)
        {
            string installlogs = Path.GetFullPath(System.Windows.Forms.Application.CommonAppDataPath);
            Process.Start("explorer.exe", installlogs);
        }

        private void treeView_products_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.F5)
            {
                if (!wpInstallRequirementsCheckforTreenode.IsBusy)
                {
                    HelperFunctions.CachedCheckInstallationRequirements.Clear(); //clear installation requirements cache before scanning
                    wpInstallRequirementsCheckforTreenode.RunWorkerAsync();
                    bgReqCheckbar.Visible = true;
                }

            }
        }


        private void notifyIcon1_Click(object sender, EventArgs e)
        {
            ShowRaktajinoBallonTip();
        }

    }
}
